# -*- coding: utf-8 -*-
#Create By hacklh, 2017/7/7
import os
import hashlib
import time
from time import sleep
class FileMonitor:

    def __init__(self, root_path, init_log_path):
        self.root_path = root_path
        self.all_files = []
        self.init_log_path = init_log_path
        self.white_list = []

    def get_file_md5(self, file_path):
        with open(file_path, 'rb') as fp:
            md5 = hashlib.md5()
            md5.update(fp.read())
            hash = md5.hexdigest()
            return str(hash)

    def get_all_files(self):
        self.all_files = []
        dirs = [self.root_path]
        while True:
            try:
                tmp_dir = dirs.pop()
                for filename in os.listdir(tmp_dir):
                    file_path = os.path.join(tmp_dir, filename)
                    if os.path.isdir(file_path):
                        dirs.append(file_path)
                        continue
                    self.all_files.append(file_path)
            except:
                break
    def start_monitor(self):
        self.get_all_files()
        self.generate_log(self.init_log_path)  #第一次执行，初始化所有日志
        with open(self.init_log_path, "r") as fp:
            for line in fp.readlines():
                self.white_list.append(line.strip())  #加载白名单

        sleep(1)
        while True:
            modify_path = []
            self.get_all_files()
            self.generate_log("tmp.txt")
            with open("tmp.txt", "r") as fp:
                for line in fp.readlines():
                    if line.strip() not in self.white_list:
                        modify_path.append(line)

            self.generate_log("modify_log.txt", modify_path)
            sleep(1)


    def generate_log(self, log_path, modify_path=[]):
        logs = []
        if not modify_path:
            for f in self.all_files:
                logs.append("{}::{}\n".format(f, self.get_file_md5(f)))
            with open(log_path, "w") as fp:
                fp.write("Write Log on : {}\n".format(time.strftime("%Y-%m-%d %X", time.localtime(time.time()))))
                fp.writelines(logs)
                fp.write('-----------------------------------------------------------------------------\n')
        else:
            with open(log_path, "a") as fp:
                fp.write("Write Log on : {}\n".format(time.strftime("%Y-%m-%d %X", time.localtime(time.time()))))
                fp.writelines(modify_path)
                fp.write('-----------------------------------------------------------------------------\n')



monitor = FileMonitor(".\\file_tset", "init_log.txt")
monitor.start_monitor()